package cn.zgwj.basic.util;

import cn.zgwj.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录上下文
 *  1.登录人信息
 *  2.登录人的权限信息
 *
 *  在非受容器管理的对象中,获取受容器管理的对象
 *
 */
public class LoginContext {
    /*@Autowired
    private RedisTemplate redisTemplate;*/

    /**
     * 获取当前登录人
     * @param request
     * @return
     */
    public static Logininfo getCurrentLogininfo(HttpServletRequest request){
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            //1.先得到Spring容器
            WebApplicationContext webApplicationContext =
                    WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            //2.通过容器获取容器中的对象
            RedisTemplate redisTemplate = (RedisTemplate) webApplicationContext.getBean("redisTemplate");
            Object loginTmp = redisTemplate.opsForValue().get(token);
            if(loginTmp != null){
                return (Logininfo) loginTmp;
            }
        }
        return null;
        /*if(StringUtils.isEmpty(token)){
            return null;
        }
        //1.先得到Spring容器
        WebApplicationContext webApplicationContext =
                WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        //2.通过容器获取容器中的对象
        RedisTemplate redisTemplate = webApplicationContext.getBean(RedisTemplate.class);
        Object loginTmp = redisTemplate.opsForValue().get(token);
        // 从redis中查询数据
        if(loginTmp == null){
            return null;
        }else{
            return (Logininfo) loginTmp;
        }*/
    }


}
